﻿/* 
ZenCoding Visual Studio AddIn
Copyright (C) 2009 Einar Egilsson
http://tech.einaregilsson.com/2009/11/12/zen-coding-visual-studio-addin/

Portions of this program (the ZenCoding Python library) were taken from
the ZenCoding project (http://code.google.com/p/zen-coding/)

Those parts are copyright (C) 2009 Sergey Chikuyonok (http://chikuyonok.ru)

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

$Id: PythonEnvironment.cs 332 2009-12-01 15:37:19Z einar@einaregilsson.com $ 
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

namespace ZenCoding.VisualStudio
{
    internal static class PythonAssemblies
    {
        private static bool initialized;
        public static void Init()
        {
            if (!initialized)
            {
                AppDomain.CurrentDomain.AssemblyResolve +=ResolveIronPythonAssemblies;
                initialized = true;
            }
        }

        static Assembly ResolveIronPythonAssemblies(object sender, ResolveEventArgs args)
        {
            string ipyFolder = Path.Combine(Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath), "IronPython");
            string filename = Path.Combine(ipyFolder, args.Name.Split(',')[0] + ".dll");
            return File.Exists(filename) ? Assembly.LoadFile(filename) : null;
        }
    }


    internal static class PythonEnvironment
    {
        private static readonly ScriptEngine engine;

        static PythonEnvironment()
        {
            var options = new Dictionary<string, object>();
#if DEBUG
            options["Debug"] = true;
#endif
            engine = Python.CreateEngine(options);
            engine.SetSearchPaths(new[] { ".", BaseFolder, Path.Combine(BaseFolder, @"IronPython\lib") });
        }

        private static string BaseFolder
        {
            get
            {
                return Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
            }
        }

        public static T CreateInstance<T>(string filename, string className)
        {
            ScriptScope scope = engine.ExecuteFile(Path.Combine(BaseFolder,filename));
            return (T)engine.Execute(className + "()", scope);
        }
    }
}
